package com.tycmc.signelectroniccontracts.tools.update;

import android.os.Environment;
import android.os.Handler;
import android.os.Message;

import com.tycmc.signelectroniccontracts.tools.images.UrlPath;
import com.tycmc.signelectroniccontracts.tools.show.LogShow;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by GY on 2018/1/21.
 */

public class NetDown {
    public static final String SIZE = "size";
    public static final String MAX = "max";
    public static final int SUCECC = 1;
    public static final int UPDATAING = 2;
    public static final int FAIL = 3;
    public static final int CANCEL = 4;
    public static Handler netHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (downloadInterface != null) {
                downloadInterface.state(msg.what,msg.obj);
            }
            switch (msg.what) {
                case SUCECC:
                    break;
                case UPDATAING:
                    break;
                case FAIL:
                    break;
                case CANCEL:
                    break;
            }
            return false;
        }
    });
    private static boolean isCancel;
    private static DownloadInterface downloadInterface;

    public static void cancelDown() {
        isCancel = false;
    }

    /*
     * 从服务器中下载APK
     */
    public static void downLoadApk(final String downUrl, DownloadInterface downloadInterface) {
        NetDown.downloadInterface = downloadInterface;
        isCancel = true;
        new Thread() {
            @Override
            public void run() {
                try {
                    File file = getFileFromServer(downUrl);
                    sleep(3000);
                    LogShow.i("cancel====");
                    if (isCancel) {
                        Message obtain = Message.obtain();
                        obtain.obj =file;
                        obtain.what =SUCECC;
                        netHandler.sendMessage(obtain);
                    } else {
                        LogShow.i("cancel====1");
                        netHandler.sendEmptyMessage(CANCEL);
                    }
                } catch (Exception e) {
                    LogShow.i("下载失败",e.getMessage());
                    Message message = Message.obtain();
                    message.what = FAIL;
                    message.obj = e.getMessage();
                    netHandler.sendMessage(message);
                    e.printStackTrace();
                }
            }
        }.start();
    }

    public static String getFile() {
        return UrlPath.DownloadPath + "UpData.apk";
    }

    /**
     * 开始下载
     *
     * @param path 路径
     * @return
     * @throws Exception
     */
    public static File getFileFromServer(String path) throws Exception {
        //如果相等的话表示当前的sdcard挂载在手机上并且是可用的
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(20000);
            int max = conn.getContentLength();
            //获取到文件的大小
//            pd.setMax(conn.getContentLength() / 1024);
//            conn.setRequestProperty();
            InputStream is = conn.getInputStream();
            File file = new File(getFile());
            FileOutputStream fos = new FileOutputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            byte[] buffer = new byte[1024];
            int len;
            int total = 0;

            while ((len = bis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
                total += len;
                if (isCancel) {
                    Map<String, Integer> map = new HashMap<>();
                    map.put(SIZE, total);
                    map.put(MAX, max);

                    Message message = Message.obtain();
                    message.what = UPDATAING;
                    message.obj = map;
                    netHandler.sendMessage(message);
                } else {
                    LogShow.i("cancel====3");
                    break;
                }

                //获取当前下载量
//                pd.setProgress(total / 1024);
            }
            fos.close();
            bis.close();
            is.close();
            return file;
        } else {
            return null;
        }
    }
}
